package ext.tianma.MaterialClassification;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.LWCUtil;
import ext.tianma.part.util.IBAUtil;
import ext.tianma.workflow.WorkItemHelper;
import wt.fc.ObjectNoLongerExistsException;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.Source;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.query.KeywordExpression;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.TypeDefinitionReference;
import wt.type.TypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import wt.vc.wip.WorkInProgressHelper;
import wt.workflow.engine.WfEngineHelper;

public class CreatePartClassificationNode implements RemoteAccess {
	// 在类型管理器中自定义的part类型
	private static String part_type = "wt.part.WTPart|cn.tianma.RawMaterial";
	private static String RFQpart_type = "wt.part.WTPart|cn.tianma.RFQPart";
	public static final String discardState = "OBSOLESCENCE";// 废弃状态
	// 产品中文件夹的路径，注意默认在文件夹前夹上Default
	private static String PartPath = "Default/AVL材料";

	public static String STATUTE_PATH = "/ptc/Windchill/codebase/ext/tianma/part/config/classIfication.xlsx";
	public static String STATUTE_PATH1 = "/ptc/Windchill/codebase/ext/tianma/part/config/AVLPartClassifiaction.xlsx";

	/***
	 * 创建AVL材料
	 * 
	 * @param avlPartNumber
	 *            材料编号
	 * @param ParentNumber
	 *            父料编号
	 * @param count
	 *            数量
	 * @param RFQNumber
	 *            RFQ编号
	 * @return
	 * @throws Exception
	 */
	public static String createPartByAVL(String avlPartNumber, String ParentNumber, String count, String RFQNumber, String firstClassification,
			String length, String width, String lwRatio, String materialThickness, String layerNumber, String purpose,
			String shape, String defaultUnit, String supplementaryMsg, String surfaceCoatingTechnology,
			String steelmakingProcess, String shapeTechnology, String polishing, String hole, String weightValue) throws Exception {
		JSONObject ob = new JSONObject();
		JSONArray array = new JSONArray();
		JSONObject obInner = new JSONObject();
		WTPart parentPart = null; // 一级料part对象
		WTPart avlPart = null; // AVLpart對象
		String avlPartNumber2 = "";

		// 獲取aVLpart對象
		if (avlPartNumber != null && ParentNumber != null) {
			System.out.println("avlPartNumber=====>>>" + avlPartNumber);
			// 如果选择多个AVL材料
			if (avlPartNumber.contains(",")) {
				String[] split = avlPartNumber.split(",");// 以逗号分割
				System.out.println(split.length);
				for (String string2 : split) {
					System.out.println("string2-->>>" + string2);
					avlPartNumber2 = string2;
				}
			} else {

			}
			System.out.println("avlPartNumber==>>" + avlPartNumber2);
			avlPart = BOMHelp.getPart(avlPartNumber2, "", "");

			// 判断是创建RFQ编号物料还是直接搭建一级料BOM
			if (!ParentNumber.isEmpty()) {
				parentPart = BOMHelp.getPart(ParentNumber, "", "");
				if (parentPart == null) {
					System.out.println("===>>start==>>");
					ob.put("status", "false");
					ob.put("message", "输入的成品编号不存在！");
					ob.put("data", "");
					return ob.toString();
				}
			} else if (ParentNumber.isEmpty()) {
				System.out.println("====>>create ==into ");
				RFQpart_type = "wt.part.WTPart|cn.tianma.RFQPart";
				// 如果创建的为RFQBOM则先检查RFQ物料是否存在，不存在则创建
				parentPart = BOMHelp.getPart(RFQNumber, "", "");
				if (parentPart == null) {
					// 區分RFQPart 為BLU還是其他類型 不同類型多建
					parentPart = CreatePartClassificationUtil.createRFQPart(PartPath, RFQpart_type, "RFQ物料", RFQNumber,firstClassification,
							avlPart);
					ParentNumber = parentPart.getNumber();
				}
			}

			String classIfaName = ""; // 分类名称
			String partEName = ""; // 中文名称

			// 以一级料码是否为空验证创建一级BOM类型 还是RFQBOM类型
			System.out.println("ParentNumber===>>" + ParentNumber);
			System.out.println("ParentNumber.isEmpty()==>>" + ParentNumber.isEmpty());

			// 验证一级料是否包含RFQ编号，如果包含则不更改

			IBAUtil ibaParentPart = new IBAUtil(parentPart);
			String rfqNumberByParentPart = ibaParentPart.getIBAValue("partRFQNumber");
			if (rfqNumberByParentPart == null) {
				ibaParentPart.setIBAValue("partRFQNumber", RFQNumber);
				ibaParentPart.updateIBAPart(parentPart);
			}

			if (avlPart != null) {

				System.out.println("avlPart111===>>>" + avlPart.getNumber());
				Map<String, String> map = CreatePartClassificationUtil.getMaterialsClassification(avlPart.getNumber());
				// 验证当前avl材料是否存在
				String nodeFileName = CreatePartClassificationUtil.getClassification(avlPart);
				System.out.println("nodeFileName====>>" + nodeFileName);
				classIfaName = nodeFileName.substring(nodeFileName.lastIndexOf("/") + 1);
				System.out.println("classIfaName===>>" + classIfaName);
				// 以AVL材料编号为条件查询当前需要创建的物料是否存在
				WTPart part = CreatePartClassificationUtil.getPartByIBAValue("APLNumber", avlPartNumber2);
				if (part == null) {
					IBAUtil ibas = new IBAUtil(avlPart);
					partEName = ibas.getIBAValue("classifictionEName");
					System.out.println("====>>" + partEName);
					System.out.println("====>>1" + partEName == null);
					if (partEName == null || partEName == "") {
						// 获取中英文名称
						System.out.println("====>>");
						partEName = CreatePartClassificationUtil.getPartEName(classIfaName);
					}
					// 获取物料编码
					String twoPartNumber = AVLPartCommandsUtils.generateRowMaterialNumber(avlPart, partEName);
					WTPart newPart = null;
					// 获取容器
					WTContainer container = null;
					QueryResult qr = CreatePartClassificationUtil.getQueryResult(WTContainer.class, WTContainer.NAME,
							"物料库");
					while (qr.hasMoreElements()) {
						container = (WTContainer) qr.nextElement();
					}
					// 获取容器的引用
					WTContainerRef ref = ref = WTContainerRef.newWTContainerRef(container);
					// 获取文件夹
					Folder folder = wt.folder.FolderHelper.service.getFolder(PartPath, ref);
					String strPartNumber = AVLPartCommandsUtils.generateRowAVLNumber(avlPart);
					System.out.println("strPartNumber====>>>" + strPartNumber);
					System.out.println("strPartNumber===>>" + strPartNumber);
					String strPartName = avlPart.getName();
					System.out.println("strPartName-=====>>" + strPartName);
					wt.vc.views.View view = ViewHelper.service.getView("Design");
					ViewReference viewRef = ViewReference.newViewReference(view);

					TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference(part_type);

					// 创建一个部件，编码与名称
					newPart = WTPart.newWTPart(twoPartNumber, strPartName);
					// 为部件设置容器
					newPart.setContainer(container);
					// 为部件设置类型
					newPart.setTypeDefinitionReference(typeDefinitionRef);
					// 为部件设置view
					newPart.setView(viewRef);
					// 是否成品
					newPart.setEndItem(false);
					// 设置单位
					QuantityUnit unit = QuantityUnit.toQuantityUnit("PCS");
					newPart.setDefaultUnit(unit);
					// 设置来源
					Source source = Source.toSource("make");
					newPart.setSource(source);
					// 为此部件设置存贮位置
					FolderHelper.assignLocation((FolderEntry) newPart, folder);

					// 保存部件，切忌不要保存两次。经常在调用完本方法之后习惯性的再保存一次，这样会出现错误。
					newPart = (WTPart) PersistenceHelper.manager.save(newPart);

					// 从数据库中提取part
					IBAUtil iba = new IBAUtil(newPart);
					iba.setIBAValue("APLNumber", avlPartNumber2);
					iba.setIBAValue("partRFQNumber", RFQNumber);
					iba.setIBAValue("twosPartNumber", strPartNumber);
					iba.updateIBAPart(newPart);
					//需关闭工作流
					//终止原编码流程
					WfEngineHelper.service.terminateObjectsRunningWorkflows(newPart);
					newPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(newPart, State.INWORK);

					newPart = (WTPart) PersistenceHelper.manager.refresh(newPart);
					

					System.out.println("map==>>" + map);
					Iterator keys = map.keySet().iterator();
					if (classIfaName != null) {
						CreatePartClassificationUtil.setClassification("wt.part.WTPart", classIfaName, newPart);
					}
					newPart = (WTPart) PersistenceHelper.manager.refresh(newPart);
					System.out.println("newPart=====>>>" + newPart.getNumber());
					while (keys.hasNext()) {
						String key = (String) keys.next();
						String value = map.get(key);
						LWCUtil.setStringIBAValue(newPart, key, value);// 对应上POL料号
					}
					obInner.put("partNumber", newPart.getNumber());
					obInner.put("material", classIfaName);
					obInner.put("RFQNumber", RFQNumber);
					obInner.put("parentNumber", ParentNumber);
					array.put(obInner);
					System.out.println("=============sucessful1=====" + array.toString());

					// //添加bomlink关系

					WTPartMaster childPartMaster = (WTPartMaster) newPart.getMaster();

					createUserLinkByPart(parentPart, childPartMaster, null, count, length, width, lwRatio,
							materialThickness, layerNumber, purpose, shape, defaultUnit, supplementaryMsg,
							surfaceCoatingTechnology, steelmakingProcess, shapeTechnology, polishing, hole, weightValue);

					if (ParentNumber != null) {
						System.out.println("ParentNumber====>>" + ParentNumber);
						ob.put("status", "success");
						ob.put("message", "创建成功！");
						ob.put("data", array);
					} else {
						ob.put("status", "false");
						ob.put("message", "创建失败,请联系管理员！");
						ob.put("data", "");
					}

				} else {
					System.out.println("ParentNumber====>>" + part.getNumber());
					ob.put("status", "success");
					ob.put("message", "创建成功！");
					obInner.put("partNumber", part.getNumber());
					obInner.put("material", classIfaName);
					obInner.put("RFQNumber", RFQNumber);
					obInner.put("parentNumber", ParentNumber);
					array.put(obInner);
					ob.put("data", array);
					System.out.println("=============sucessful2=====" + ob.toString());

					// //添加bomlink关系

					WTPartMaster childPartMaster = (WTPartMaster) part.getMaster();

					createUserLinkByPart(parentPart, childPartMaster, null, count, length, width, lwRatio,
							materialThickness, layerNumber, purpose, shape, defaultUnit, supplementaryMsg,
							surfaceCoatingTechnology, steelmakingProcess, shapeTechnology, polishing, hole, weightValue);
				}
			} else {
				ob.put("status", "false");
				ob.put("message", "AVL材料不存在，请联系管理员");
				ob.put("data", "");
			}
		} else

		{
			ob.put("status", "false");
			ob.put("message", "AVL材料编号或者成品型号不能为空！");
			ob.put("data", "");
		}
		System.out.println("ob.toString()====>>" + ob.toString());
		return ob.toString();
	}

	/***
	 * * 删除两个零件间的使用关系
	 * 
	 * @param parPart
	 *            父阶零件
	 * @param childPart
	 *            子阶零件
	 */
	public static String deletePartLink(String childNumber, String parentNumber) {
		JSONObject ob = new JSONObject();
		try {
			WTPart childPart = BOMHelp.getPart(childNumber, "", "");
			WTPart parentPart = BOMHelp.getPart(parentNumber, "", "");

			WTPartUsageLink link = null;
			if (parentPart != null && childPart != null) {
				System.out.println("===>>delete===>>");
				try {
					link = findWTPartUsageLink(parentPart, childPart);
					if (hasWTPartUsageLink(parentPart, childPart)) {
						System.out.println("====>> jianchu ==>>");
						GenericUtil.checkout(parentPart);
						WTPart part = (WTPart) WorkInProgressHelper.service.workingCopyOf(parentPart);
						link = findWTPartUsageLink(part, childPart);
						PersistenceHelper.manager.delete(link);
						GenericUtil.checkin(parentPart);
						System.out.println("sucessful=====<<<");

					}

				} catch (WTException e) {
					e.printStackTrace();
				} catch (WTPropertyVetoException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			ob.put("status", "success");
			ob.put("message", "刪除成功！");
			ob.put("data", "");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return ob.toString();
	}

	/***
	 * 根據二級分類名稱獲取當前BOM屬性集
	 * 
	 * @param classifiName
	 * @return
	 */
	public static String getBOMIbaValuesForExcel(String classifiName,String firstClassification) {
		// 遍历excel
//		classifiName = "导光板塑胶粒子";
		System.out.println("===>>start==>>action===>>");
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		JSONArray array = new JSONArray();
		JSONObject ob = new JSONObject();
		try {
			System.out.println("CASCADE_PATH===>>" + STATUTE_PATH1);
			is = new FileInputStream(STATUTE_PATH1);

			System.out.println("=====>>>" + STATUTE_PATH1);
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				// 2003及以下
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				// 2007及以上
				wb = new XSSFWorkbook(is);
			} else {
				// 不是Excel
				throw new WTException("Incorrect configuration file path.");
			}

			workbook = wb;

			Sheet sheet = workbook.getSheetAt(0);
			Row row;
			Cell cell1;

			// 第一行为表头，从第二行开始遍历
			for (int i = 1, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
				System.out.println("row===>>" + i);
				if ((row = sheet.getRow(i)) != null) {
					// 遍历列
					String classiciNameForExcel = "";
					String classiciNameForExcel2 = "";
					int cellNum = row.getLastCellNum();
					System.out.println("cellNum===>>" + cellNum);
					cell1 = row.getCell(1);
					//classiciNameForExcel = cell1.getStringCellValue();
					classiciNameForExcel = getCellValue(row.getCell(1)).trim();
					classiciNameForExcel2 = getCellValue(row.getCell(0)).trim();
					// 判断当前二级分类名称是否属于当前excel 然后将符合分类的BOM属性封装成json key为中文 value为英文
					System.out.println("classiciNameForExcel====>>" + classiciNameForExcel);
					if (classifiName.equals(classiciNameForExcel)&&firstClassification.equals(classiciNameForExcel2)) {
						JSONObject obInner = new JSONObject();
						System.out.println("row.getCell(3)====>>" + row.getCell(3));
						if ("Y".equals(getCellValue(row.getCell(3)))) {
							obInner = new JSONObject();
							obInner.put("researchName","length");
							obInner.put("showName", "长（mm）");
							array.put(obInner);
							System.out.println("array=====>>" + array.toString());
						}

						if ("Y".equals(getCellValue(row.getCell(4)))) {
							obInner = new JSONObject();
							obInner.put("researchName","width");
							obInner.put("showName", "宽(mm)");
							array.put(obInner);
							System.out.println("array2=====>>" + array.toString());
						}
						if ("Y".equals(getCellValue(row.getCell(5)))) {
							obInner = new JSONObject();
							obInner.put("researchName","lenthAndWidth");
							obInner.put("showName", "长宽比例");
							array.put(obInner);
							System.out.println("array3=====>>" + array.toString());
						}
						if ("Y".equals(getCellValue(row.getCell(6)))) {
							obInner = new JSONObject();
							obInner.put("researchName","tostiong");
							obInner.put("showName", "材料厚度(mm)");
							array.put(obInner);
							System.out.println("array4=====>>" + array.toString());
						}
						if ("Y".equals(getCellValue(row.getCell(7)))) {
							obInner = new JSONObject();
							obInner.put("researchName", "count");
							obInner.put("showName", "数量");
							array.put(obInner);
							System.out.println("array5=====>>" + array.toString());
						}
						if ("Y".equals(getCellValue(row.getCell(8)))) {
							obInner = new JSONObject();
							obInner.put("researchName","supplementaryMsg");
							obInner.put("showName", "补充信息");
							array.put(obInner);
							System.out.println("array6=====>>" + array.toString());
						}
						if ("Y".equals(getCellValue(row.getCell(9)))) {
							obInner = new JSONObject();
							obInner.put("researchName","surfaceCoatingTechnology");
							obInner.put("showName", "表面镀膜工艺");
							array.put(obInner);
						}
						if ("Y".equals(getCellValue(row.getCell(10)))) {
							obInner = new JSONObject();
							obInner.put("researchName", "steelmakingProcess");
							obInner.put("showName", "钢化工艺");
							array.put(obInner);
						}
						if ("Y".equals(getCellValue(row.getCell(11)))) {
							obInner = new JSONObject();
							obInner.put("researchName","shapeTechnology");
							obInner.put("showName", "外形工艺");
							array.put(obInner);
						}
						if ("Y".equals(getCellValue(row.getCell(12)))) {
							obInner = new JSONObject();
							obInner.put("researchName","polishing");
							obInner.put("showName", "是否抛光");
							array.put(obInner);
						}
						if ("Y".equals(getCellValue(row.getCell(13)))) {
							obInner = new JSONObject();
							obInner.put("researchName","hole");
							obInner.put("showName", "孔数");
							array.put(obInner);
						}

						if ("Y".equals(getCellValue(row.getCell(14)))) {
							obInner = new JSONObject();
							obInner.put("researchName", "layerNumber");
							obInner.put("showName", "层数");
							array.put(obInner);
						}
						if ("Y".equals(getCellValue(row.getCell(15)))) {
							obInner = new JSONObject();
							obInner.put("researchName","shape");
							obInner.put("showName", "形状");
							array.put(obInner);
						}
						if ("Y".equals(getCellValue(row.getCell(16)))) {
							obInner = new JSONObject();
							obInner.put("researchName","weightValue");
							obInner.put("showName", "重量");
							array.put(obInner);
						}
						if ("Y".equals(getCellValue(row.getCell(17)))) {
							obInner = new JSONObject();
							obInner.put("researchName","purpose");
							obInner.put("showName", "功能用途");
							array.put(obInner);
						}
						break;
					}
				}
			}
			ob.put("status", "success");
			ob.put("message", "查询成功！");
			ob.put("data", array);
			System.out.println("ob====>>" + ob.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(is);
		}

		return ob.toString();

	}

	/***
	 * 根據零部件編號獲取零部件并設置狀態啓動BOM發佈流程
	 * 
	 * @param partNumber
	 * @return
	 */
	public static String setPartlifestyleToCommit(String partNumber) {
		JSONObject ob = new JSONObject();
		try {
			WTPart parentPart = BOMHelp.getPart(partNumber, "", "");
			parentPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(parentPart, State.INWORK);
			parentPart = (WTPart) PersistenceHelper.manager.refresh(parentPart);
			ob.put("status", "false");
			ob.put("message", "設置成功！");
			ob.put("data", "");
		} catch (ObjectNoLongerExistsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ob.toString();
	}

	/***
	 * 根據零部件編號獲取零部件并設置狀態啓動BOM鞥改流程
	 * 
	 * @param partNumber
	 * @return
	 */
	public static String setPartlifestyleToChange(String partNumber) {
		JSONObject ob = new JSONObject();
		try {
			WTPart parentPart = BOMHelp.getPart(partNumber, "", "");
			parentPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(parentPart, State.INWORK);
			parentPart = (WTPart) PersistenceHelper.manager.refresh(parentPart);
			ob.put("status", "false");
			ob.put("message", "設置成功！");
			ob.put("data", "");
		} catch (ObjectNoLongerExistsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ob.toString();
	}

	/**
	 * 检验零件是否存在使用关系
	 * 
	 * @param parPart
	 *            父阶零件
	 * @param childPart
	 *            子阶零件
	 * @return 是否存在使用关系
	 */
	@SuppressWarnings("deprecation")
	public static boolean hasWTPartUsageLink(WTPart parPart, WTPart childPart) {
		boolean hasUsageLink = false;
		QueryResult qr = null;
		WTPartUsageLink link = null;
		WTPartMaster master = null;
		if (parPart != null && childPart != null) {
			try {
				qr = WTPartHelper.service.getUsesWTPartMasters(parPart);
				while (qr.hasMoreElements()) {
					System.out.println("====>>== ==>>");
					link = (WTPartUsageLink) qr.nextElement();
					master = (WTPartMaster) link.getUses();
					if (childPart.getMaster().equals(master)) {
						hasUsageLink = true;
						break;
					}
				}
			} catch (WTException e) {
				e.printStackTrace();
			}
		}

		return hasUsageLink;
	}

	/**
	 * 获取指定零件的使用关系
	 * 
	 * @param parPart
	 *            父阶零件
	 * @param childPart
	 *            子阶零件
	 * @return
	 */
	public static WTPartUsageLink findWTPartUsageLink(WTPart parPart, WTPart childPart) {
		WTPartUsageLink link = null;
		QueryResult qr = null;
		WTPartMaster master = null;

		if (parPart != null && childPart != null) {
			try {
				qr = WTPartHelper.service.getUsesWTPartMasters(parPart);
				while (qr.hasMoreElements()) {
					link = (WTPartUsageLink) qr.nextElement();
					master = (WTPartMaster) link.getUses();
					if (childPart.getMaster().equals(master)) {
						break;
					}
				}
			} catch (WTException e) {
				e.printStackTrace();
			}
		}

		return link;
	}

	/***
	 * 获取随机编码
	 * 
	 * @return
	 * @throws WTException
	 */
	public static String getCascade(WTPart part) throws WTException {
		String partNumber = "";
		String Orderno = null;
		System.out.println("===>>start==>>action===>>");
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		try {
			System.out.println("CASCADE_PATH===>>" + STATUTE_PATH);
			is = new FileInputStream(STATUTE_PATH);

			System.out.println("=====>>>" + STATUTE_PATH);
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				// 2003及以下
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				// 2007及以上
				wb = new XSSFWorkbook(is);
			} else {
				// 不是Excel
				throw new WTException("Incorrect configuration file path.");
			}

			workbook = wb;

			Sheet sheet = workbook.getSheetAt(0);
			Row row;
			Cell cell1, cell2, cell;
			String tempVal;

			// 第一行为表头，从第二行开始遍历
			for (int i = 2, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
				if ((row = sheet.getRow(i)) != null) {
					// 遍历列
					String finishedGoodResolutionCode = "";
					String fbl_W = "";
					int cellNum = row.getLastCellNum();
					String str = "";
					for (int j = 0; j <= cellNum; j++) {
						cell = row.getCell(j);
						cell1 = row.getCell(0);
						cell2 = row.getCell(1);
						System.out.println("cell1===>>" + cell1);
						System.out.println("cell2===>>" + cell2);
						if (cell1 == null || (tempVal = cell1.getStringCellValue()) == null || cell2 == null
								|| (tempVal = cell2.getStringCellValue()) == null) {
							str = "";
						} else {
							finishedGoodResolutionCode = cell1.getStringCellValue();
							System.out.println("finishedGoodResolutionCode====>>" + finishedGoodResolutionCode);
							fbl_W = cell2.getStringCellValue();
							System.out.println("fbl_W====>>" + fbl_W);
							String nodeFileName = CreatePartClassificationUtil.getClassification(part);
							System.out.println("nodeFileName====>>" + nodeFileName);
							if (finishedGoodResolutionCode.equals(nodeFileName)) {
								System.out.println("===>>start===");
								partNumber = fbl_W;
							}
						}
					}

				}
			}
			// 生成六位流水碼
			System.out.println("partNumber====>>" + partNumber);
			String maxOrderno = getAVLMaterial(partNumber); // 从数据库查询出的最大编号
			System.out.println("maxOrderno=" + maxOrderno);
			int endNum = Integer.parseInt(maxOrderno); // 把String类型的0001转化为int类型的1
			System.out.println("endNum=" + endNum);
			int tmpNum = 100000 + endNum + 1; // 结果1000002
			System.out.println("tmpNum=" + tmpNum);
			Orderno = partNumber + CreatePartClassificationUtil.subStr("" + tmpNum, 1);// 把10002首位的1去掉，再拼成NO201601260002字符串
			System.out.println("Orderno====>>" + Orderno);
			System.out.println("fblMap====>>>" + partNumber);
			return Orderno;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new WTException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new WTException(e);
		} finally {
			close(is);
		}
	}
	/**
	 * 获取单元格中的信息
	 * 
	 * @param cell 单元格
	 * @return 主要参数信息
	 * @throws Exception
	 */
	public static String getCellValue(Cell cell) throws WTException {
		String value = "";
		try {
			if (null == cell) {
				return "";
			}
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_NUMERIC:
				value = Double.toString(cell.getNumericCellValue());
				break;
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = Boolean.toString(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				try {
					value = String.valueOf(cell.getNumericCellValue());
				} catch (Exception e) {
					value = cell.getStringCellValue();
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}

		return value.trim();
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 创建关联关系，维护BOM属性
	 * 
	 * @param parentPart
	 * @param childPartMaster
	 * @param hashtable
	 * @param count
	 * @param length
	 * @param width
	 * @param lwRatio
	 * @param materialThickness
	 * @param layerNumber
	 * @param purpose
	 * @param shape
	 * @param defaultUnit
	 * @param supplementaryMsg
	 * @param surfaceCoatingTechnology
	 * @param steelmakingProcess
	 * @param shapeTechnology
	 * @param polishing
	 * @param hole
	 * @param weightValue
	 */
	public static void createUserLinkByPart(WTPart parentPart, WTPartMaster childPartMaster, Hashtable hashtable,
			String count, String length, String width, String lwRatio, String materialThickness, String layerNumber,
			String purpose, String shape, String defaultUnit, String supplementaryMsg, String surfaceCoatingTechnology,
			String steelmakingProcess, String shapeTechnology, String polishing, String hole, String weightValue) {
		System.out.println("start int ======>>>");
		System.out.println("parentPart==>>" + parentPart);
		System.out.println("count===>>" + count);
		if (count.isEmpty()) {
			count = "1";
		}

		try {
			WTPartUsageLink newlink = WTPartUsageLink.newWTPartUsageLink(parentPart, childPartMaster);
			double quanty = Double.parseDouble(count);
			QuantityUnit qu = null;
			if (childPartMaster != null) {
				qu = childPartMaster.getDefaultUnit();
			}
			Quantity qtity = Quantity.newQuantity(quanty, qu);
			newlink.setQuantity(qtity);
			PersistenceServerHelper.manager.insert(newlink);
			IBAUtil iba = new IBAUtil(newlink);
			System.out.println("length====>>" + length);
			if (length != null) {
				iba.setIBAValue("length", length);
			}
			System.out.println("width====>>" + width);
			if (width != null) {
				iba.setIBAValue("widths", width);
			}
			System.out.println("lwRatio====>>" + lwRatio);
			if (lwRatio != null) {
				iba.setIBAValue("lwRatio", lwRatio);
			}
			System.out.println("materialThickness====>>" + length);
			if (materialThickness != null) {
				iba.setIBAValue("materialThickness", materialThickness);
			}
			System.out.println("layerNumber" + length);
			if (layerNumber != null) {
				iba.setIBAValue("layerNumber", layerNumber);
			}
			System.out.println("purpose====>>" + purpose);
			if (purpose != null) {
				iba.setIBAValue("purpose", purpose);
			}
			System.out.println("shape====>>" + shape);
			if (shape != null) {
				iba.setIBAValue("shape", shape);
			}
			System.out.println("defaultUnit====>>" + defaultUnit);
			if (defaultUnit != null) {
				iba.setIBAValue("defaultUnit", defaultUnit);
			}
			System.out.println("supplementaryMsg====>>" + supplementaryMsg);
			if (supplementaryMsg != null) {
				iba.setIBAValue("supplementaryMsg", supplementaryMsg);
			}
			System.out.println("surfaceCoatingTechnology====>>" + surfaceCoatingTechnology);
			if (surfaceCoatingTechnology != null) {
				iba.setIBAValue("surfaceCoatingTechnology", surfaceCoatingTechnology);
			}
			System.out.println("steelmakingProcess====>>" + steelmakingProcess);
			if (steelmakingProcess != null) {
				iba.setIBAValue("steelmakingProcess", steelmakingProcess);
			}
			System.out.println("shapeTechnology====>>" + shapeTechnology);
			if (shapeTechnology != null) {
				iba.setIBAValue("shapeTechnology", shapeTechnology);
			}
			System.out.println("polishing====>>" + polishing);
			if (polishing != null) {
				iba.setIBAValue("polishing", polishing);
			}
			System.out.println("hole====>>" + hole);
			if (hole != null) {
				iba.setIBAValue("hole", hole);
			}
			System.out.println("weightValue====>>" + weightValue);
			if (weightValue != null) {
				iba.setIBAValue("weightValue", weightValue);
			}
			iba.setIBAValue("bomIba", "111");
			iba.updateIBAPart(newlink);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getAVLMaterial(String ifinodeClassName) {
		System.out.println("======>>>>star");
		List<Integer> list = new ArrayList<Integer>();
		String MaxStr = "";
		try {
			QuerySpec qs = new QuerySpec();
			int docIndex = qs.appendClassList(WTPart.class, true);
			View view = ViewHelper.service.getView("Design");
			SearchCondition scState = new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE,
					SearchCondition.NOT_EQUAL, discardState);
			qs.appendWhere(scState, new int[] { 0 });
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			QueryResult qr = PersistenceHelper.manager.find(qs);
			System.out.println("======>>>>start44===>>updateIBAValue" + qs);
			System.out.println("======>>>>start55===>>updateIBAValue" + qr.size());
			int count = 1;
			while (qr.hasMoreElements()) {
				System.out.println("count==>>" + count);
				Object obj[] = (Object[]) qr.nextElement();
				if (obj[0] instanceof WTPart) {
					WTPart part = (WTPart) obj[0];
					System.out.println("===>>>" + part.getNumber());
					System.out.println("ifinodeClassName===>>>" + ifinodeClassName);
					if (part.getNumber().startsWith(ifinodeClassName)) {
						String partNumber = part.getNumber().substring(part.getNumber().length() - 6);
						String strNumber = "1" + partNumber;
						int number = Integer.parseInt(strNumber);
						list.add(number);
					}
				}
			}
			int max = 0;
			for (int i = 0; i < list.size(); i++) {
				list.get(0);
				if (list.get(i) > max) {
					max = list.get(i);
				}
			}
			MaxStr = CreatePartClassificationUtil.subStr("" + max, 1);
			System.out.println("MaxStr====>>" + MaxStr);
		} catch (QueryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return MaxStr;
	}

	public static String getPartUrlByNumber(String partNumber) {
		JSONObject ob = new JSONObject();
		try {
			WTPart avlPart = BOMHelp.getPart(partNumber, "", "");
			if (avlPart != null) {
				// 调用获取url方法
				String partUrl = WorkItemHelper.generateInfoPageURL(avlPart);
				System.out.println("====>>>partUrl==>>" + partUrl);
				ob.put("status", "sucess");
				ob.put("message", "创建成功！");
				ob.put("data", partUrl);
			} else {
				ob.put("status", "false");
				ob.put("message", "创建失敗！");
				ob.put("data", "");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ob.toString();

	}
}
